package org.jiangy.authentication.filter;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.jiangy.authentication.JwtUtils;
import org.jiangy.usercenter.UserDetailsProxy;
import org.jose4j.jwt.JwtClaims;
import org.jose4j.jwt.MalformedClaimException;
import org.jose4j.jwt.consumer.InvalidJwtException;
import org.springframework.http.HttpHeaders;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextHolderStrategy;
import org.springframework.security.web.context.RequestAttributeSecurityContextRepository;
import org.springframework.security.web.context.SecurityContextRepository;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 * TODO: 可以利用 OAuth2 Resource Server 的 `BearerTokenAuthenticationFilter`、`JwtAuthenticationProvider` 工具来实现相同功能，更好的支持 JWT。
 * 解析 JWT 并从中恢复用户登录状态到 SecurityContext
 * <p>创建时间: 2024/8/12 </p>
 *
 * @author <a href="mailto:jiangliu0316@outlook.com" rel="nofollow">蒋勇</a>
 */
public class JwtAuthenticationFilter extends OncePerRequestFilter {
    private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder
            .getContextHolderStrategy();
    private SecurityContextRepository securityContextRepository = new RequestAttributeSecurityContextRepository();

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // Bearer xxx.xxx.xxx
        String authorizationValue = request.getHeader(HttpHeaders.AUTHORIZATION);
        if (!StringUtils.hasText(authorizationValue)) {
            filterChain.doFilter(request, response);
            return;
        }
        authorizationValue = authorizationValue.replace("Bearer ", "");
        try {
            JwtClaims claims = JwtUtils.INSTANCE.parseJwt(authorizationValue);
            // TODO: 可以从 Redis 中恢复登录的用户信息
            String userJsonValue = claims.getClaimValue("user", String.class);
            UserDetailsProxy<?> authenticatedUser = UserDetailsProxy.create(userJsonValue);
            // 显示处理用户类型
            UsernamePasswordAuthenticationToken authenticationResult = new UsernamePasswordAuthenticationToken(authenticatedUser, null, authenticatedUser.getAuthorities());
            // 认证成功后将用户信息存储到安全上下文
            SecurityContext context = this.securityContextHolderStrategy.createEmptyContext();
            context.setAuthentication(authenticationResult);
            this.securityContextHolderStrategy.setContext(context);
            this.securityContextRepository.saveContext(context, request, response);

            filterChain.doFilter(request, response);
        } catch (MalformedClaimException | InvalidJwtException e) {
            throw new RuntimeException(e);
        }

    }
}
